<template>
  <div class="login-page">
    <!-- 背景图 -->
    <div class="bg-image"></div>


    <div class="login-card">
      <a-card title="用户登录" style="width: 400px; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.15)">
        <a-form ref="formRef" layout="vertical">
          <a-form-item label="用户名" name="username" :validate-status="errors.username ? 'error' : ''"
            :help="errors.username">
            <a-input v-model:value="username" placeholder="请输入用户名" size="large" />
          </a-form-item>

          <a-form-item label="密码" name="password" :validate-status="errors.password ? 'error' : ''"
            :help="errors.password">
            <a-input-password v-model:value="password" placeholder="请输入密码" size="large" />
          </a-form-item>

          <a-form-item>
            <a-button type="primary" size="large" block @click="loginAndAuthorize" :loading="loading">
              登录
            </a-button>
          </a-form-item>

          <a-divider>或者</a-divider>

          <a-button type="default" size="large" block @click="">
            注册
          </a-button>
        </a-form>
      </a-card>
    </div>
  </div>
</template>


<script lang="ts" setup>
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ref, computed } from 'vue';
import { generatePKCE } from '@/utils/pkce';

const authority = import.meta.env.VITE_AUTHORITY as string;
const clientId = import.meta.env.VITE_CLIENT_ID as string;
const redirectUri = import.meta.env.VITE_REDIRECT_URI as string;
const scope = import.meta.env.VITE_SCOPE as string;
const identityurl = import.meta.env.VITE_API_IDENTITY as string;
const username = ref('');
const password = ref('');

const loading = ref(false);
const errors = reactive<{ username?: string; password?: string }>({})
const canSubmit = computed(() => username.value.trim() !== '' && password.value !== '');

function sanitizeReturnPath(path: string | null): string {
  if (!path) return '/';
  try {
    const u = new URL(path, window.location.origin);
    if (u.origin !== window.location.origin) return '/';
    return u.pathname + u.search + u.hash;
  } catch {
    return '/';
  }
}

async function loginAndAuthorize() {
  // 清空上次错误
  errors.username = ''
  errors.password = ''

  let hasError = false

  if (!username.value.trim()) {
    errors.username = '请输入用户名'
    hasError = true
  }
  if (!password.value) {
    errors.password = '请输入密码'
    hasError = true
  }

  if (hasError) return

  loading.value = true;
  try {
    // 1. 本地登录
    const loginResp = await fetch(`${identityurl}/api/auth/login`, {
      method: 'POST',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        username: username.value.trim(),
        password: password.value,
      }),
    });

    const result = await loginResp.json();
    if (!result.isSuccess) {
      errors.password = result.errors?.join('\n') || '登录失败';
      return;
    }

    const temp_token = result.data?.temp_token;
    if (!temp_token) {
      errors.password = '登录成功但未收到 temp_token';
      return;
    }

    sessionStorage.setItem('temp_token', temp_token);

    // 2. 生成 PKCE + state
    const state = crypto.randomUUID();
    const { codeVerifier, codeChallenge } = await generatePKCE();

    sessionStorage.setItem('pkce_state', state);
    sessionStorage.setItem('pkce_verifier', codeVerifier);


    // 3. 跳转 authorize
    const tempToken = sessionStorage.getItem('temp_token');
    const params = new URLSearchParams({
      response_type: 'code',
      client_id: clientId,
      redirect_uri: redirectUri,
      scope: scope,
      state,
      code_challenge: codeChallenge,
      code_challenge_method: 'S256',
      temp_token: tempToken || '',
    });

    window.location.href = `${identityurl}/connect/authorize?${params.toString()}`;
  } catch (e: any) {
    errors.password = e.message || '未知错误';
  } finally {
    loading.value = false;
  }
}




</script>

<style scoped>
.login-page {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

/* 背景图全屏 */
.bg-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('https://picsum.photos/1920/1080');
  background-size: cover;
  background-position: center;
  filter: brightness(0.7);
  z-index: -1;
}

/* 登录卡片以中轴线为基准靠右显示 */
.login-card {
  position: absolute;
  top: 50%;
  left: 50%;
  /* 先移到中点 */
  transform: translate(150px, -50%);
  /* translateX 为偏移到中轴线右侧，可调节距离屏幕中轴线 */
  z-index: 1;
}

/* 小屏幕可居中 */
@media (max-width: 768px) {
  .login-card {
    transform: translate(-50%, -50%);
  }
}
</style>
